package com.atguigu.gulimail.member.controller;

import com.atguigu.common.exception.BizCodeEnum;
import com.atguigu.common.to.GiteeMemberVo;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.R;
import com.atguigu.gulimail.member.entity.MemberEntity;
import com.atguigu.gulimail.member.exception.ExistPhoneException;
import com.atguigu.gulimail.member.exception.ExistUsernameException;
import com.atguigu.gulimail.member.service.MemberService;
import com.atguigu.gulimail.member.vo.UserRegistVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.Map;



/**
 * 会员
 *
 * @author fangyi
 * @email 2244210628@qq.com@gmail.com
 * @date 2022-08-10 09:21:04
 */
@RestController
@RequestMapping("member/member")
public class MemberController {

    @Autowired
    private MemberService memberService;

    /**
     * 列表
     */
    @RequestMapping("/oauth2/login")
    public R GiteeSaveOrRegit(@RequestBody GiteeMemberVo giteeMemberVo){

        MemberEntity memberEntity = memberService.GiteeSaveOrRegit(giteeMemberVo);

        if(memberEntity != null){
            return R.ok().setData(memberEntity);
        }

        return R.error(BizCodeEnum.UNKNOW_EXCEPTION.getCode(), BizCodeEnum.UNKNOW_EXCEPTION.getMsg());
    }



    @RequestMapping("/list")
    public R list(@RequestParam Map<String, Object> params){
        PageUtils page = memberService.queryPage(params);

        return R.ok().put("page", page);
    }



    /**
     * 信息
     */
    @RequestMapping("/info/{id}")
    public R info(@PathVariable("id") Long id){
		MemberEntity member = memberService.getById(id);

        return R.ok().put("member", member);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    public R save(@RequestBody MemberEntity member){
		memberService.save(member);

        return R.ok();
    }

    @RequestMapping("/regist")
    public R saveUer(@RequestBody UserRegistVo userRegistVo){


        try {
            memberService.saveUser(userRegistVo);
        }catch (ExistUsernameException e){
            return R.error(BizCodeEnum.VAILD_USERNAME_EXCEPTION.getCode(),BizCodeEnum.VAILD_USERNAME_EXCEPTION.getMsg());
        }catch (ExistPhoneException e){
            return R.error(BizCodeEnum.VAILD_PHONE_EXCEPTION.getCode(),BizCodeEnum.VAILD_PHONE_EXCEPTION.getMsg());
        }

        return R.ok();
    }


    /**
     * 修改
     */
    @RequestMapping("/update")
    public R update(@RequestBody MemberEntity member){
		memberService.updateById(member);

        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    public R delete(@RequestBody Long[] ids){
		memberService.removeByIds(Arrays.asList(ids));

        return R.ok();
    }

}
